package com.bckj.fastboot.paid.biz.domain.refund.execution;

import com.bckj.fastboot.core.execution.Execution;
import com.bckj.fastboot.core.execution.ExecutionContext;
import com.bckj.fastboot.paid.api.constant.RefundExecutionNames;
import com.bckj.fastboot.paid.api.entity.RefundOrder;
import com.bckj.fastboot.paid.api.enums.RefundStatusEnum;
import com.bckj.fastboot.paid.api.exceptions.RefundException;
import com.bckj.fastboot.paid.api.model.RefundRequest;
import com.bckj.fastboot.paid.api.model.RefundResponse;
import com.bckj.fastboot.paid.biz.domain.pay.provider.RefundGatewayProvider;
import com.bckj.fastboot.paid.biz.domain.refund.context.RefundContext;
import com.bckj.fastboot.paid.biz.domain.refund.repo.RefundOrderRepository;
import com.bckj.fastboot.paid.biz.infrastructure.convert.RefundOrderConvert;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class RefundOrderCreateExecution implements Execution {

    private final RefundOrderRepository refundOrderRepository;
    private final RefundOrderConvert refundOrderConvert;

    @Override
    public String getName() {
        return RefundExecutionNames.REFUND_ORDER_CREATE;
    }

    @Override
    public void execute(ExecutionContext context) {
        RefundContext ctx = (RefundContext) context;
        RefundRequest request = ctx.getRequest();
        RefundOrder refundOrder = refundOrderConvert.toRefundOrder(request);
        try {
            RefundResponse refundResponse = RefundGatewayProvider.get(request.getRefundWay()).refund(request);
            refundOrder.setStatus(RefundStatusEnum.REFUNDING.getCode());
            ctx.setResponse(refundResponse);
        } catch (RefundException e) {
            log.error("退款异常", e);
            refundOrder.setStatus(RefundStatusEnum.REFUND_FAIL.getCode());
        }
        refundOrderRepository.save(refundOrder);
    }
}
